import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @Author YuanYuan
 * @Date 2022/11/28
 * @Time 12:50
 */
@WebServlet("/user")
public class UserServlet extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");
        String blogId = req.getParameter("blogId");
        if(null == blogId) {
            //博客列表页
            try {
                getUserFromSession(req,resp);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }else {
            //博客详情页
            try {
                getUserFromSql(req,resp,blogId);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

    private void getUserFromSql(HttpServletRequest req, HttpServletResponse resp, String blogId) throws SQLException, IOException {

        Blog blog = BlogDAO.selectOne(Integer.parseInt(blogId));
        if(null == blog) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("该博客不存在");
            return;
        }
        User user = UserDAO.selectById(blog.getUserId());
        if(null == user) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("该用户不存在");
            return;
        }
        user.setUserBlog(BlogDAO.userblogcount(user.getUserId()));
        resp.getWriter().write(objectMapper.writeValueAsString(user));
    }

    private void getUserFromSession(HttpServletRequest req, HttpServletResponse resp) throws IOException, SQLException {
        HttpSession httpSession = req.getSession(false);
        if(null == httpSession) {
            resp.getWriter().write("未登录");
            return;
        }
        User user = (User) httpSession.getAttribute("user");
        if(null == user) {
            resp.getWriter().write("未登录");
            return;
        }
        user.setUserPassword("");
        user.setUserBlog(BlogDAO.userblogcount(user.getUserId()));
        resp.getWriter().write(objectMapper.writeValueAsString(user));
    }
}
